<template>
  <div>
    <basic-container>
      <!--昨日订单优化-->
      <div id="yesterdayOfferBar" :style="{width: '100%', height: '400px'}" style="margin-top: 20px">暂无数据</div>
    </basic-container>
    <basic-container>
      <div id="yesterdayOptimizerPie" :style="{width: '100%', height: '400px'}" style="margin-top: 20px"></div>
      <div>
        <div style="display: flex">
          <div class="dateLable">每天报告 :</div>
          <el-date-picker
            id="id-dataroport-charsreport-dailyCostChange"
            v-model="dailyCostDate"
            type="daterange"
            size="mini"
            clearable="false"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="dailyCostChange"
          >
          </el-date-picker>
        </div>
        <div class="offerInFo">订单统计</div>
        <div id="offerDaily" :style="{width: '100%', height: '400px'}" style="margin-top: 20px"></div>
        <div class="offerInFo">优化师统计</div>
        <div id="optimizerDaily" :style="{width: '100%', height: '400px'}" style="margin-top: 20px"></div>
      </div>
    </basic-container>
    <basic-container>
      <div class="search">
        <div style="display: flex;flex-wrap: wrap;">
          <div class="platformForm-search-border">
            <div class="dateLable">每天报告 :</div>
            <el-date-picker
              id="id-dataroport-charsreport-initDailyReport"
              v-model="platformForm.date"
              type="daterange"
              size="mini"
              clearable="false"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
              :default-time="['00:00:00', '23:59:59']" @change="initDailyReport">
            </el-date-picker>
          </div>
          <div class="platformForm-search-border">
            <div class="dateLable">订单:</div>
            <el-select id="id-dataroport-charsreport-changeOfferId"
                       size="mini" v-model="platformForm.offerId" clearable filterable @change="changeOfferId">
              <el-option v-for="(item,index) in options.offerList" :key="index" :label="item.name === '全部' ? item.name
              :item.name + ' ('+item.id + ')'" :value="item.id"></el-option>
            </el-select>
          </div>
          <div class="platformForm-search-border">
            <div class="dateLable">优化师 :</div>
            <el-select id="id-dataroport-charsreport-changeOmId"
                       size="mini" v-model="platformForm.userId" clearable filterable @change="changeOmId">
              <el-option v-for="(item,index) in options.omList" :key="index" :label="item.name === '全部' ? item.name:
              item.name + ' ('+item.id + ')'" :value="item.id"></el-option>
            </el-select>
          </div>
          <div class="platformForm-search-border">
            <div class="dateLable">账户 :</div>
            <el-select id="id-dataroport-charsreport-dailyCostChange"
                       size="mini" multiple v-model="platformForm.accountIds" style="width: 250px" clearable filterable
                       @change="changeAccount">
              <el-option v-for="(item,index) in options.accountList" :key="index" :label="item.name === '全部' ? item.name:
              item.name + ' ('+item.platform_id + ')'" :value="item.id"></el-option>
            </el-select>
          </div>
        </div>
      </div>
      <div style="display: flex;justify-content: space-between">
        <div id="facebookPlatform" :style="{width: '49%', height: '400px'}" style="margin-top: 20px"></div>
        <div id="googlePlatform" :style="{width: '49%', height: '400px'}" style="margin-top: 20px"></div>
      </div>
      <div id="sumPlatform" :style="{width: '100%', height: '400px'}" style="margin-top: 20px"></div>
    </basic-container>
  </div>
</template>

<script>
import * as echarts from "echarts";
import Moment from 'moment'

import {getOfferList} from "@/api/business/share"
import {getOfferCost, getOmCost, getDailyReport, dailyReportOptions} from "@/api/dataReport/chartsReport";
import {getOptimizer} from "@/api/offer/creative";

import {mapGetters} from "vuex";

export default {
  name: "iconReport",
  data() {
    return {
      options: {
        offerList: [],
        omList: [],
        accountList: [''],
      },
      dailyCostDate: [],
      yesterdayOfferCost: {
        nameList: [],
        costList: [],
      },
      yesterdayOmCost: {
        nameList: [],
        costList: [],
        dailyDate: [],
      },
      dailyOfferCost: {
        nameList: [],
        costList: [],
        dailyCost: {},
      },
      dailyOmCost: {
        nameList: [],
        costList: [],
        dailyDate: [],
      },
      dailyReport: {
        dailyDate: [],
        gg: {
          costList: [],
          installList: [],
          impressionList: [],
          clickList: []
        },
        fb: {
          costList: [],
          installList: [],
          impressionList: [],
          clickList: []
        },
        total: {
          costList: [],
          installList: [],
          impressionList: [],
          clickList: []
        },
      },

      platformForm: {
        date: [],
        offerId: '',
        userId: '',
        accountIds: [],
      }
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initCharts();
      this.initSelectOptions();
    })
    this.platformForm.accountIds = ['']
  },
  computed: {
    ...mapGetters(["userInfo"]),
  },
  methods: {
    /**
     * 优化师昨日花费日期回调
     */
    dailyCostChange() {
      this.initOfferDailyCost(this.dailyCostDate[0], this.dailyCostDate[1]);
      this.initOmDailyCost(this.dailyCostDate[0], this.dailyCostDate[1]);
    },
    /**
     * 修改订单
     */
    changeOfferId() {
      this.platformForm.userId = ''
      this.platformForm.accountIds = ['']
      this.getAccountSelectOption();
      this.initDailyReport()
    },

    /**
     * 修改优化师
     */
    changeOmId() {
      this.platformForm.accountIds = ['']
      this.getAccountSelectOption();
      this.initDailyReport()
    },

    /**
     * 修改账户
     */
    changeAccount(val) {
      if (val.indexOf('') !== -1 && val.length > 1) {
        if (val[val.length - 1] === '') {
          this.platformForm.accountIds = ['']
        } else {
          this.platformForm.accountIds.splice(val.findIndex(item => item === ''), 1)
        }
      }
      this.initDailyReport()
    },

    initSelectOptions() {
      getOfferList(this.userInfo.user_id).then(res => {
        this.options.offerList = [{name: '全部', id: '',}, ...res.data.data]
      });
      this.getAccountSelectOption()
    },


    getAccountSelectOption() {
      dailyReportOptions({offerId: this.platformForm.offerId, omId: this.platformForm.userId}).then(res => {
        this.options.omList = [{name: '全部', id: ''}, ...res.data.data.omList];
        this.options.accountList = [{name: '全部', id: ''}, ...res.data.data.accountOptions];
      })
    },
    /**
     * 初始化每日花费数据
     */
    initOfferDailyCost(startDate, endDate) {
      let isYesterday = startDate === endDate
      getOfferCost(startDate, endDate).then(res => {
        let offerCostList = res.data.data;
        if (isYesterday) {
          this.yesterdayOfferCost = offerCostList;
          this.initYesterdayOfferLine();
        } else {
          this.dailyOfferCost = offerCostList;
          this.initDaily("offerDaily");
        }
      });
    },

    /**
     * 初始化每日花费数据
     */
    initOmDailyCost(startDate, endDate) {
      let isYesterday = startDate === endDate
      getOmCost(startDate, endDate).then(res => {
        let omCostList = res.data.data;
        if (isYesterday) {
          this.yesterdayOmCost = omCostList;
          this.initYesterdayOptimizerPie();
        } else {
          this.dailyOmCost = omCostList;
          this.initDaily("optimizerDaily");
        }

      })
    },
    /**
     * 初始化每日报表数据
     */
    initDailyReport() {
      let params = {
        startDate: this.platformForm.date[0],
        endDate: this.platformForm.date[1],
        offerId: this.platformForm.offerId,
        userId: this.platformForm.userId,
        accountIds: this.platformForm.accountIds.join(',')
      }

      getDailyReport(params).then(res => {
        this.dailyReport = res.data.data;
        this.initPlatformLine("googlePlatform", 'Google', this.dailyReport.gg)
        this.initPlatformLine('facebookPlatform', 'FaceBook', this.dailyReport.fb)
        this.initPlatformLine('sumPlatform', "汇总", this.dailyReport.total)
      });
    },

    /**
     * 初始化图表
     */
    initCharts() {
      //初始化昨日订单列表
      //1. 初始化时间默认为前7天
      let last7Date = Moment(new Date()).add(-7, 'days').format('YYYY-MM-DD');
      let yesterday = Moment(new Date()).add(-1, 'days').format('YYYY-MM-DD');
      this.dailyCostDate = [last7Date, yesterday]
      this.platformForm.date = [last7Date, yesterday]
      // 2. 初始化昨天的订单花费数据
      this.initOfferDailyCost(yesterday, yesterday);
      // // 3. 初始化昨天优化师的花费数据
      this.initOmDailyCost(yesterday, yesterday);
      // // 4. 初始化每天订单的花费
      this.initOfferDailyCost(last7Date, yesterday);
      // // 5. 初始化每天优化师的花费
      this.initOmDailyCost(last7Date, yesterday);
      // 6. 初始化dailyReport
      this.initDailyReport()
    },
    getEchartsInst(eleName) {
      let ele = document.getElementById(eleName);
      let myInst = echarts.getInstanceByDom(ele);
      if(myInst) {
        return myInst;
      } else {
        return echarts.init(ele);
      }
    },
    /**
     *
     * 初始化昨日订单列表
     */
    initYesterdayOfferLine() {
      let myChart = this.getEchartsInst('yesterdayOfferBar');
      let option
      let offerNameList = this.yesterdayOfferCost.nameList;
      option = {
        title: {
          text: this.yesterdayOfferCost.costList.length === 0 ? "暂无数据" : '昨日订单花费',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {            // 坐标轴指示器，坐标轴触发有效
            type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
          }
        },
        xAxis: {
          type: 'category',
          data: this.yesterdayOfferCost.nameList,
          axisLabel: {
            interval: 0,
            rotate: 40
          },
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        yAxis: {
          type: 'value'
        },
        series: [{
          data: this.yesterdayOfferCost.costList,
          itemStyle: {
            color: function(params) {
              let colorList = [];
              for (let i = 0; i<=offerNameList.length; i++){
                colorList[i] = "#"+Math.floor(Math.random()*0xFFFFFF).toString(16).padStart(6,"0");
              }
              return colorList[params.dataIndex]
            },
          },
          type: 'bar'
        }]
      };
      option && myChart.setOption(option);
    },
    /**
     * 初始化昨日优化师花费
     */
    initYesterdayOptimizerPie() {
      let pieData = [];
      let nameList = this.yesterdayOmCost.nameList;
      let costList = this.yesterdayOmCost.costList;
      if (nameList.length > 0) {
        for (let i = 0; i < nameList.length; i++) {
          let param = {};
          param['value'] = costList[i];
          param['name'] = nameList[i];
          pieData.push(param);
        }
      }
      let myChart = this.getEchartsInst('yesterdayOptimizerPie');
      let option
      option = {
        color: ["#FE2E2E","#FE9A2E","#F7FE2E","#40FF00","#00FFFF","#0080FF","#DF01D7","#0101DF","#04B431", "#8A0829",
          "#BDBDBD","#F781F3","#81F7F3","#ACFA58","#FAAC58","#DBA901","#DF01A5","#E2A9F3","#FA58AC","#2EFEF7"],
        title: {
          text:  pieData.length === 0 ? '暂无数据':'优化师昨日花费',
          left: 'center'
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b} : {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left',
        },
        series: [
          {
            name: '访问来源',
            type: 'pie',
            radius: '50%',
            data: pieData,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      };
      option && myChart.setOption(option);
    },
    /**
     * 初始化每日日报
     */
    initDaily(id) {
      let dailyCostObj = id === 'offerDaily' ? this.dailyOfferCost : this.dailyOmCost;
      let nameList = dailyCostObj.nameList;
      let dailyDate = dailyCostObj.dailyDate;
      let costObj = dailyCostObj.dailyCost;
      let seriesArr = [];
      for (let key in costObj) {
        let val = costObj[key];
        let series = {
          name: key,
          type: 'bar',
          stack: 'total',
          emphasis: {
            focus: 'series'
          },
          data: val
        };
        seriesArr.push(series);
      }
      let myChart = this.getEchartsInst(id);
      let option;
      option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {            // Use axis to trigger tooltip
            type: 'shadow'        // 'shadow' as default; can also be 'line' or 'shadow'
          }
        },
        legend: {
          type:'scroll',
          width: '85%',
          data: nameList,
          selector: [{
            type: 'all or inverse',
            // 可以是任意你喜欢的 title
            title: '全选'
            },
            {
              type: 'inverse',
              title: '反选'
            }],
          selectorLabel: {
            fontSize: 12,
            lineHeight: 17,
            width: 26,
            height: 17,
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'value'
        },
        yAxis: {
          type: 'category',
          data: dailyDate
        },
          series: seriesArr
      };

      option && myChart.setOption(option);
      if(seriesArr.length === 0){
        myChart.setOption(option,true)
      }
    },
    /**
     * 初始化媒体折线图
     */
    initPlatformLine(id, title, platformData) {
      let myChart = this.getEchartsInst(id);
      let option
      option = {
        title: {
          text:platformData.impressionList.length === 0&& platformData.clickList.length === 0
          && platformData.installList.length === 0&& platformData.costList.length === 0 ? '暂无数据' : title
        },
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: ['曝光', '点击', '安装', '花费'],
          selected: {
            '曝光': false
          }
        },
        grid: {
          left: '5%',
          right: '12%', //   调整大小
          bottom: '3%',
          containLabel: true
        },

        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: this.dailyReport.dailyDate,
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '曝光',
            type: 'line',
            smooth: true,
            data: platformData.impressionList,
            lineStyle:{
              color:'#A9F5BC'
            },
            itemStyle : {
              normal : {
                color:'#81F79F'
              }
            },
            areaStyle: {
              normal: {
                color: {
                  x: 0,
                  y: 0,
                  x2: 0,
                  y2: 1,
                  colorStops: [{
                    offset: 0,
                    color: "#E0F8EC" // 0% 处的颜色
                  }, {
                    offset: 0.7,
                    color: "#EFFBFB" // 100% 处的颜色
                  }],
                  globalCoord: false // 缺省为 false
                }
              }
            },
          },
          {
            name: '点击',
            type: 'line',
            smooth: true,
            data: platformData.clickList,
            lineStyle:{
              color:'#58FAF4'
            },
            itemStyle : {
              normal : {
                color:'#00FFFF'
              }
            },
            areaStyle: {
              normal: {
                color: {
                  x: 0,
                  y: 0,
                  x2: 0,
                  y2: 1,
                  colorStops: [{
                    offset: 0,
                    color: "#A9F5F2" // 0% 处的颜色
                  }, {
                    offset: 0.7,
                    color: "#E0F8F7" // 100% 处的颜色
                  }],
                  globalCoord: false // 缺省为 false
                }
              }
            },
          },
          {
            name: '安装',
            type: 'line',
            smooth: true,
            data: platformData.installList,
            lineStyle:{
              color:'#F2F5A9'
            },
            itemStyle : {
              normal : {
                color:'#FFFF00'
              }
            },
            areaStyle: {
              normal: {
                color: {
                  x: 0,
                  y: 0,
                  x2: 0,
                  y2: 1,
                  colorStops: [{
                    offset: 0,
                    color: "#F5F6CE" // 0% 处的颜色
                  }, {
                    offset: 0.7,
                    color: "#FBFBEF" // 100% 处的颜色
                  }],
                  globalCoord: false // 缺省为 false
                }
              }
            },
          },
          {
            name: '花费',
            type: 'line',
            smooth: true,
            data: platformData.costList,
            lineStyle:{
              color:'#FAAC58'
            },
            itemStyle : {
              normal : {
                color:'#FFBF00'
              }
            },
            areaStyle: {
              normal: {
                color: {
                  x: 0,
                  y: 0,
                  x2: 0,
                  y2: 1,
                  colorStops: [{
                    offset: 0,
                    color: "#F5D0A9" // 0% 处的颜色
                  }, {
                    offset: 0.7,
                    color: "#F8ECE0" // 100% 处的颜色
                  }],
                  globalCoord: false // 缺省为 false
                }
              }
            },
          }
        ]
      };
      option && myChart.setOption(option);
    },
  }
}
</script>

<style scoped>
.dateLable {
  border-radius: 4px;
  border: 1px solid rgb(220, 223, 230);
  padding: 3px 10px;
  font-size: 14px;
  height: 20px;
  margin-right: 10px;
}
.offerInFo {
  width: 100%;
  height: 60px;
  line-height: 80px;
  font-size:20px;
  font-weight: bold;
}

.platformForm-search-border {
  display: flex;
  margin-left: 10px;
  margin-top: 10px
}
</style>
